package com.rimi.controller.CookieInterceptor;

import com.rimi.bean.User;
import com.rimi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @
 * @author:liangLi
 * @time:2020/7/7 12:41
 */
public class CookieInterceptor implements HandlerInterceptor {

    @Autowired
    UserService userService;
    /**
     *  处理程序调用之前
     *      类似于doFilter
     *      如果有多个拦截器，先执行所有的preHandle，再执行所有的postHandle，在执行视图渲染一次，最后执行所有的afterCompletion
     * @param request
     * @param response
     * @param handler
     * @return  是否通过当前拦截，false通不过，true通过
     * @throws Exception
     */

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception{
        System.out.println("处理器执行前");

        Cookie[] cookies=request.getCookies();

        String userId=null;

        if (cookies!=null){
            for (Cookie cookie : cookies) {
                if ("Id".equals(cookie.getName())){
                    userId=cookie.getValue();
                }
            }
        }


        if (null!=userId){
            int  number  = Integer.valueOf(userId);
            User user = userService.findUserById(number);

            request.getSession().setAttribute("user",user);
        }
        return true;
    }

}
